<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>通过审批后继续编辑销售订单</title>
<script type="text/javascript">
    var oriSaleTypeDiscount = null;
    var curSaleTypeDiscount = null;
    //此角色的最大折扣权限。
    var roleDiscount = <%=session[:role].discount%>;
    //是否临时保存
    var oriSaleTypeId = null;
    Ext.onReady(function () {
        var authentication = Ext.create('Ext.form.field.Hidden', {
            name: 'authentication',
            value: 0
        });

        var saleOrderId = Ext.create('Ext.form.field.Hidden', {
            name: 'id'
        });

        var version = Ext.create('Ext.form.field.Hidden', {
            name: 'lock_version'
        });

        //备注
        var desc = Ext.create('Ext.form.field.Text', {
            fieldLabel: '备注',
            name: 'description',
            anchor: '97%'
        });

        //出库说明
        var deliveryDesc = Ext.create('Ext.form.field.Text', {
            fieldLabel: '出库说明',
            name: 'delivery_desc',
            anchor: '100%'
        });

        //所有客户
        var toCustomer = Ext.create('Ext.form.ComboBox', {
            fieldLabel: '到客户',
            store: customerAllInfoStore,
            allowBlank: false,
            blankText: "客户必须选择",
            emptyText: '请选择...',
            valueField: 'id',
            displayField: 'name',
            name: 'customer_id',
            loadingText: '搜索中...',
            minChars: 0,
            anchor: '100%',
            listConfig: {
                getInnerTpl: function () {
                    return '<div style="float:left; width:60px">{number}</div><div style="float:left;width:150px">|{name:ellipsis(12)}</div>| {phone:ellipsis(28)}';
                }
            },
            pageSize: 10
        });


        toCustomer.on('select', function (combo, record, index) {
            if (record[0].get('linkman') === "") {
                linkman.setValue(record[0].get('name'));
            } else {
                linkman.setValue(record[0].get('linkman'));
            }
            phone.setValue(record[0].get('phone'));
            deliveryAddress.setValue(record[0].get('address'));
        });

        var addCustomerButton = Ext.create('Ext.Button', {
            text: '添加客户',
            iconCls: 'addItem',
            scale: 'small',
            handler: onAddCustomerButtonClick
        });

        function onAddCustomerButtonClick() {
            newCustomerWin = Ext.create('Ext.window.Window', {
                layout: 'fit',
                width: 618,
                height: 300,
                closeAction: 'destroy',
                plain: true,
                modal: true,
                constrain: true,
                //modal: true,
                title: '添加客户',
                autoLoad: {
                    url: "/customer/newCustomer",
                    scripts: true
                }
            });
            newCustomerWin.resizable = false;
            newCustomerWin.show();
        }

        //销售类型
        var saleType = Ext.create('Ext.form.ComboBox', {
            store: saleTypeStore,
            fieldLabel: '销售类型',
            allowBlank: false,
            blankText: "销售类型必须选择",
            emptyText: '请选择...',
            valueField: 'id',
            displayField: 'name',
            name: 'sale_type_id',

            loadingText: '搜索中...',
            anchor: '95%',
            editable: false,
            minChars: 0
        });

        saleType.on('select', function (combo, record, index) {
            //这里要判断有一种情况是要从新取得价格，给grid中的单价设置上价格，然后用resetPrice再从新设置一下。
            //oriSaleTypeDiscount != null代表了不是第一次选择。oriSaleTypeId != record[0].get('id')代表进行了不同的选择。
            if (oriSaleTypeDiscount != null && oriSaleTypeId != record[0].get('id')) {
                //这里一但销售类型变化 ，都要从新取一次价格，然后从新变更价格
                var saleTypeId = record.get('id');
                var productIdStr = getFieldStringFromGridStore(saleOrderDetailDS, 'product_id');
                Ext.Ajax.request({
                    url: '/product/getPricesBySTIdPIds',
                    success: function (result, request) {
                        //先把标志位置清空
                        clearFieldValueForGridStore(saleOrderDetailDS, 'sale_type_price', -1);
                        if (Ext.JSON.decode(result.responseText).root.length != 0) {
                            for (var i = 0; i < Ext.JSON.decode(result.responseText).root.length; i++) {
                                var productPrice = Ext.JSON.decode(result.responseText).root[i];
                                var saleOrderDetailRecords = saleOrderDetailDS.find('product_id', productPrice.product_id);
                                if (saleOrderDetailRecords.length > 0) {
                                    var saleOrderDetailRecord = saleOrderDetailRecords.get(0);
                                    //sale_type_price，现在是替换基准价。
                                    saleOrderDetailRecord.set('sale_type_price', productPrice.unit_price);
                                }
                            }
                        }

                        curSaleTypeDiscount = record.get('discount');
                        resetPrice();
                    },
                    failure: function (result, request) {
                        Ext.MessageBox.show({
                            title: '消息',
                            msg: "通讯失败，请从新操作",
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.WARNING
                        });
                    },
                    method: 'POST',
                    params: {
                        sale_type_id: saleTypeId,
                        product_ids: productIdStr,
                        authenticity_token: authToken.getValue()
                    }
                });
            }

            if (curSaleTypeDiscount == null) {
                curSaleTypeDiscount = record.get('discount');
            }
            oriSaleTypeDiscount = curSaleTypeDiscount;
            oriSaleTypeId = record.get('id');
        });


        //销售策略
        var salesStrategy = Ext.create('Ext.form.ComboBox', {
            store: salesStrategyStore,
            fieldLabel: '销售策略',
            allowBlank: false,
            blankText: "销售策略必须选择",
            emptyText: '请选择...',
            valueField: 'id',
            displayField: 'name',
            name: 'sales_strategy_id',

            loadingText: '搜索中...',
            anchor: '95%',
            editable: false,
            minChars: 0
        });

        //要求发货时间
        var actionDate = Ext.create('Ext.form.field.Date', {
            fieldLabel: '发货日期',
            name: 'action_date',
            format: 'Y-m-d', //格式化日期
            //disabledDays: [0,6],	//不让选择周六，周日
            //disabledDaysText: "周末要休息",
            invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
            allowBlank: false,
            blankText: "发货日期必须选择",
            emptyText: '发货日期...',
            anchor: '95%'
        });
        //合同号
        var contractNumber = Ext.create('Ext.form.field.Text', {
            fieldLabel: '合同编号',
            allowBlank: true,
            name: 'contract_number',
            anchor: '95%'
        });

        //联系人
        var linkman = Ext.create('Ext.form.field.Text', {
            fieldLabel: '联系人',
            name: 'linkman',
            allowBlank: false,
            anchor: '95%'
        });

        //联系电话
        var phone = Ext.create('Ext.form.field.Text', {
            fieldLabel: '联系电话',
            name: 'phone',
            allowBlank: false,
            anchor: '95%'
        });

        //税率
        var taxRate = Ext.create('Ext.form.field.Number', {
            fieldLabel: '税率(%)',
            name: "tax_rate",
            allowBlank: false,
            allowDecimals: true,
            minValue: 0,
            maxValue: 100,
            anchor: '95%'
        });

        var deliveryAddress = Ext.create('Ext.form.field.Text', {
            fieldLabel: '送货地址',
            allowBlank: false,
            name: 'delivery_address',
            anchor: '97%'
        });

        //销售员
        var sales = Ext.create('Ext.form.ComboBox', {
            store: employeeStore,
            fieldLabel: '销售员',
            allowBlank: false,
            blankText: "销售员必须选择",
            emptyText: '请选择...',
            valueField: 'id',
            displayField: 'name',
            name: 'sales_id',
            editable: false,
            loadingText: '搜索中...',
            anchor: '95%',
            minChars: 0
        });

        //业绩部门
        var sellDept = Ext.create('Ext.form.ComboBox', {
            store: departmentStore,
            fieldLabel: '业绩部门',
            allowBlank: false,
            blankText: "业绩部门必须选择",
            valueField: 'department_id',
            displayField: 'name',
            name: 'sell_dept_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
            emptyText: '请选择...',
            editable: false,
            loadingText: '搜索中...',
            anchor: '95%',
            //pageSize: 10,
            readOnly: false,
            minChars: 0
        });

        //总金额
        var sumAmount = Ext.create('Ext.form.field.Number', {
            fieldLabel: '总金额',
            name: "amount",
            readOnly: true,
            allowBlank: false,
            allowDecimals: true,
            minValue: 0,
            anchor: '90%'
        });

        //已付金额
        var recAmount = Ext.create('Ext.form.field.Number', {
            fieldLabel: '已付金额',
            name: "rec_amount",
            readOnly: true,
            allowBlank: true,
            allowDecimals: true,
            minValue: 0,
            anchor: '90%'
        });

        //--------------------------------------------------------------------------
        //产品
        var productCBB = Ext.create('Ext.form.ComboBox', {
            store: productAllInfoStore,
            fieldLabel: '产品',
            emptyText: '请选择...',
            valueField: 'id',
            displayField: 'name',
            name: 'product_id',
            loadingText: '搜索中...',
            anchor: '100%',
            pageSize: 10,
            minChars: 0,
            listConfig: {
                loadingText: 'Searching...',
                getInnerTpl: function () {
                    return '<div style="float:left; width:200px" data-qtip="{name}">{name:ellipsis(18)}</div><div style="float:left; width:110px">{number}</div>{is_suit}';
                }
            }
        });

        //供应商产品
        var productCBB = Ext.create('Ext.form.ComboBox', {
            store: productAllInfoStore,
            emptyText: '请选择...',
            displayField: 'name',
            loadingText: '搜索中...',
            anchor: '100%',
            minChars: 0,
            listConfig: {
                loadingText: 'Searching...',
                getInnerTpl: function () {
                    return '<div style="float:left; width:200px" data-qtip="{name}">{name:ellipsis(18)}</div><div style="float:left; width:110px">{number}</div>{is_suit}';
                }
            },
            pageSize: 10
        });

        productCBB.on('select', function (combo, record, index) {
                var records = saleOrderDetailGrid.getSelectionModel().getSelection();
                var saleOrderItemRecord = records[0];
                if (!saleOrderItemRecord) {
                    return false;
                }

                if (isDuplicateByProduct(saleOrderDetailDS, record[0].get('id'), saleOrderItemRecord.id)) {
                    //删除当前记录
                    if (saleOrderItemRecord.get('product_id') != record[0].get('id')) {
                        saleOrderDetailDS.remove(saleOrderItemRecord);
                    }
                } else {
                    if (saleOrderItemRecord.get('product_id') != record[0].get('id')) {
                        saleOrderItemRecord.set('number', record[0].get('number'));
                        saleOrderItemRecord.set('spec', record[0].get('spec'));
                        saleOrderItemRecord.set('unit', record[0].get('unit'));
                        saleOrderItemRecord.set('quantity', 1);
                        saleOrderItemRecord.set('ori_unit_price', record[0].get('unit_price'));

                        saleOrderItemRecord.set('discount', 1);
                        saleOrderItemRecord.set('product_id', record[0].get('id'));
                        //判断套装
                        saleOrderItemRecord.set('is_suit', record[0].get('is_suit'));

                        //单价要特别拿出来处理,如果有销售类型的价格则使用，如果没有就使用销售类型的通用折扣。
                        Ext.Ajax.request({
                            url: '/product/getPricesBySTIdPIds',
                            success: function (result, request) {
                                if (Ext.JSON.decode(result.responseText).root.length != 0) {
                                    var productPrice = Ext.JSON.decode(result.responseText).root[0];
                                    saleOrderItemRecord.set('unit_price', productPrice.unit_price);
                                } else {
                                    saleOrderItemRecord.set('unit_price', Math.round(1000 * record[0].get('unit_price') * curSaleTypeDiscount) / 1000);
                                }
                                saleOrderItemRecord.set('amount', saleOrderItemRecord.get('unit_price'));
                            },
                            failure: function (result, request) {
                                Ext.MessageBox.show({
                                    title: '消息',
                                    msg: "通讯失败，请从新操作",
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.WARNING
                                });
                            },
                            method: 'POST',
                            params: {
                                sale_type_id: oriSaleTypeId,//oriSaleTypeId在这儿就是指上次选择的值。
                                product_ids: record[0].get('id'),
                                authenticity_token: authToken.getValue()
                            }
                        });
                    }
                }
        });

        //销售订单列表Grid Store
        var saleOrderDetailDS = Ext.create('Ext.data.Store', {
            autoDestroy: true,
            model: 'SaleOrderDetailEditModel',
            proxy: {
                type: 'ajax',
                url: '/sale_order/getSaleOrderDetailsById',
                extraParams: {'sale_order_id': <%=params[:id]%>},
                reader: {
                    type: 'json',
                    root: 'root',
                    totalProperty: 'totalProperty'// 数据集记录总数
                }
            },
            autoLoad: true
        });

        //生成要订单的产品的Grid
        //生成要订单的产品的Grid
        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1
        });

        var saleOrderDetailGrid = Ext.create('Ext.grid.Panel', {
            store: saleOrderDetailDS,
            plugins: [cellEditing],
            columns: [Ext.create('Ext.grid.RowNumberer'), {
                header: '产品名称',
                dataIndex: 'product_name',
                field: productCBB,
                width: 370
            }, {
                header: '产品ID',
                dataIndex: 'product_id',
                width: 50,
                hidden: true
            }, {
                header: '产品编号',
                dataIndex: 'number',
                width: 80
            }, {
                header: '规格',
                dataIndex: 'spec',
                width: 50
            }, {
                header: '单位',
                dataIndex: 'unit',
                width: 40
            }, {
                header: '数量',
                align: 'right',
                dataIndex: 'quantity',
                field: Ext.create('Ext.form.field.Number', {
                    allowBlank: false,
                    allowDecimals: false,
                    minValue: 1
                }),
                align: 'right',
                width: 50
            }, {
                header: '单价',
                dataIndex: 'unit_price',
                renderer: Ext.util.Format.numberRenderer('0,000.00'),
                align: 'right',
                width: 90
            }, {
                header: '折扣',
                dataIndex: 'discount',
                renderer: Ext.util.Format.numberRenderer('0,000.000'),
                field: Ext.create('Ext.form.field.Number', {
                    allowBlank: false,
                    allowDecimals: true,
                    minValue: 0,
                    decimalPrecision: 6
                }),
                width: 70
            }, {
                header: '金额',
                dataIndex: 'amount',
                align: 'right',
                field: Ext.create('Ext.form.field.Number', {
                    allowBlank: false,
                    allowDecimals: true,
                    minValue: 0
                }),
                renderer: Ext.util.Format.numberRenderer('0,000.00'),
                width: 90
            }, {
                header: '套装或单品',
                dataIndex: 'is_suit',
                width: 70
            }, {
                header: '备注',
                dataIndex: 'description',
                width: 60,
                field: Ext.create('Ext.form.field.Text', {
                    name: 'description',
                    anchor: '90%'
                })
            }],
            selModel: Ext.create('Ext.selection.CheckboxModel'),
            width: 1065,
            height: 265,
            tbar: [
                {
                    text: '添加产品',
                    iconCls: 'addItem',
                    handler: function () {
                        var record = Ext.create('SaleOrderDetailEditModel', {product_name: '请选择产品'});
                        saleOrderDetailDS.insert(0, record);
                    }
                },
                {
                    text: '删除',
                    iconCls: 'remove',
                    handler: function () {
                        var records = saleOrderDetailGrid.getSelectionModel().getSelection();
                        cellEditing.cancelEdit();
                        saleOrderDetailDS.remove(records);
                        getSumAmount();
                    }
                }
            ]
        });

        //提交
        var submitButton = Ext.create('Ext.Button', {
            text: '提交所有更改',
            tooltip: '提交销售订单的包含产品在内的所有更改信息。',
            iconCls: 'icon-save',
            handler: function () {
                if (sales.getRawValue() === sales.getValue()) {
                    sales.reset();
                }

                if (toCustomer.getRawValue() === toCustomer.getValue()) {
                    toCustomer.reset();
                }

                if (sellDept.getRawValue() === sellDept.getValue()) {
                    sellDept.reset();
                    return;
                }

                if (saleOrderFormPanel.form.isValid()) {
                    var productsJsonStr = gridStoreToJson(saleOrderDetailDS, rejectKeyArray);
                    if (saleOrderDetailDS.getCount() == 0 || productsJsonStr === "") {
                        Ext.MessageBox.show({
                            title: '提示',
                            msg: "您还没有选择有效的产品或选择的产品数量为0！",
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.INFO
                        });
                        return;
                    }

                    //在提交前检查折扣有没有小于系统规定折扣的。
                    authentication.setValue(0);
                    var records = saleOrderDetailDS.getRange(0, saleOrderDetailDS.getCount());
                    var isUnsafeDiscountSubmit = false;
                    for (var i = 0; i < records.length; i++) {
                        var record = records[i];
                        var discount = record.get('discount');
                        if (parseFloat(discount) < parseFloat(roleDiscount)) {
                            isUnsafeDiscountSubmit = true;
                            break;
                        }
                    }

                    if (isUnsafeDiscountSubmit == true) {
                        Ext.MessageBox.confirm("提示", "您输入的产品折扣中有小于系统要求" + roleDiscount + "折的，请点击'否'从新检查后再提交，或点击'是'提交后将进入折扣授信审批。", function (btn) {
                            if (btn == "yes") {
                                authentication.setValue(1);
                                submitButton.disable();
                                var allJsonStr = saleOrderFormPanel.getForm().getValues();
                                allJsonStr = Ext.JSON.encode(allJsonStr);
                                allJsonStr = Ext.util.Format.substr(allJsonStr, 0, allJsonStr.length - 1);
                                allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
                                //alert(allJsonStr);
                                Ext.Ajax.request({
                                    url: '/sale_order/updateAfterAudit',
                                    success: function (result, request) {
                                        //Ext.MessageBox.alert("提示","提交成功");
                                        if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                                            Ext.MessageBox.show({
                                                title: '消息',
                                                msg: "保存销售订单，操作成功！",
                                                buttons: Ext.MessageBox.OK,
                                                icon: Ext.MessageBox.INFO
                                            });
                                        }
                                        else {
                                            Ext.MessageBox.show({
                                                title: '消息',
                                                msg: Ext.JSON.decode(result.responseText).info,
                                                buttons: Ext.MessageBox.OK,
                                                icon: Ext.MessageBox.WARNING
                                            });
                                        }
                                        editSaleOrderAfterAuditWin.destroy();
                                    },
                                    failure: function (result, request) {
                                        Ext.MessageBox.show({
                                            title: '消息',
                                            msg: "通讯失败，请从新操作",
                                            buttons: Ext.MessageBox.OK,
                                            icon: Ext.MessageBox.WARNING
                                        });
                                        editSaleOrderAfterAuditWin.destroy();
                                    },
                                    method: 'POST',
                                    params: {
                                        data: Ext.JSON.encode(allJsonStr),
                                        authenticity_token: authToken.getValue()
                                    }
                                });
                            } else {
                                return;
                            }
                        });
                    } else {
                        var allJsonStr = saleOrderFormPanel.getForm().getValues();
                        allJsonStr = Ext.JSON.encode(allJsonStr);
                        allJsonStr = Ext.util.Format.substr(allJsonStr, 0, allJsonStr.length - 1);
                        allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
                        //alert(allJsonStr);
                        Ext.Ajax.request({
                            url: '/sale_order/updateAfterAudit',
                            success: function (result, request) {
                                //Ext.MessageBox.alert("提示","提交成功");
                                if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                                    Ext.MessageBox.show({
                                        title: '消息',
                                        msg: "保存销售订单，操作成功！",
                                        buttons: Ext.MessageBox.OK,
                                        icon: Ext.MessageBox.INFO
                                    });
                                }
                                else {
                                    Ext.MessageBox.show({
                                        title: '消息',
                                        msg: Ext.JSON.decode(result.responseText).info,
                                        buttons: Ext.MessageBox.OK,
                                        icon: Ext.MessageBox.WARNING
                                    });
                                }
                                editSaleOrderAfterAuditWin.destroy();
                            },
                            failure: function (result, request) {
                                Ext.MessageBox.show({
                                    title: '消息',
                                    msg: "通讯失败，请从新操作",
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.WARNING
                                });
                                editSaleOrderAfterAuditWin.destroy();
                            },
                            method: 'POST',
                            params: {
                                data: Ext.JSON.encode(allJsonStr),
                                authenticity_token: authToken.getValue()
                            }
                        });
                    }
                }
            }
        });

        //保存编辑后的基础按钮
        var baseInfoSaveButton = Ext.create('Ext.Button', {
            text: '保存基本信息',
            tooltip: '保存销售订单非产品类基本信息。',
            iconCls: 'temp-save',
            handler: function () {
                if (sales.getRawValue() === sales.getValue()) {
                    sales.reset();
                }

                if (toCustomer.getRawValue() === toCustomer.getValue()) {
                    toCustomer.reset();
                }
                if (saleOrderFormPanel.form.isValid()) {
                    this.disable();
                    saleOrderFormPanel.form.submit({
                        success: function (result, resp) {
                            if (resp.result.info.indexOf("成功") >= 0) {
                                Ext.MessageBox.show({
                                    title: '消息',
                                    msg: "保存销售订单基本信息，操作成功！",
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.INFO
                                });
                            } else {
                                Ext.MessageBox.show({
                                    title: '消息',
                                    msg: resp.result.info,
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.WARNING
                                });
                            }
                            editSaleOrderAfterAuditWin.destroy();
                        },
                        failure: function (result, request) {
                            Ext.MessageBox.show({
                                title: '消息',
                                msg: "通讯失败，请从新操作",
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.WARNING
                            });
                            editSaleOrderAfterAuditWin.destroy();
                        }
                    });
                }
            }
        });

        //暂时保存按钮
        var closeButton = Ext.create('Ext.Button', {
            text: '关闭',
            tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
            iconCls: 'exit',
            handler: function () {
                editSaleOrderAfterAuditWin.destroy();
            }
        });

        //采购申请的FormPanel
        var saleOrderFormPanel = Ext.create('Ext.form.Panel', {
            //baseCls: 'x-plain',
            //renderTo: 'edit_sale_order_after_audit',
            fieldDefaults: {
                labelWidth: 55,
                labelAlign: 'right'
            },
            width: '1080',
            frame: true,
            url: '/sale_order/updateBaseInfoAfterAudit',
            method: 'GET',
            reader: Ext.create('Ext.data.reader.Json', {
                model: 'SaleOrderModel',
                root: 'root'
            }),
            //defaultType: 'textfield',
            items: [
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: .6,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [toCustomer]
                        },
                        {
                            columnWidth: .2,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [addCustomerButton]
                        },
                        {
                            columnWidth: .2,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [contractNumber]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: .25,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [linkman]
                        },
                        {
                            columnWidth: .35,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [phone]
                        },
                        {
                            columnWidth: .2,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [actionDate]
                        },
                        {
                            columnWidth: .2,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [taxRate]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: .6,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [deliveryAddress]
                        },
                        {
                            columnWidth: .2,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [saleType]
                        },
                        {
                            columnWidth: .2,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [sales]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: .6,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [desc]
                        },
                        {
                            columnWidth: .2,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [salesStrategy]
                        },
                        {
                            columnWidth: .2,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [sellDept]
                        }
                    ]
                },
                deliveryDesc,
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: 1,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [saleOrderDetailGrid]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: 0.2,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [sumAmount]
                        },
                        {
                            columnWidth: 0.2,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [recAmount]
                        }
                    ]
                },
                saleOrderId,
                authentication,
                version
            ],
            buttons: [submitButton, baseInfoSaveButton, closeButton]
        });

        saleOrderFormPanel.getForm().load({
            url: '/sale_order/getSaleOrderById?id=' + <%=params[:id]%>,
            method: 'GET',
            waitMsg: '正在载入数据...',
            success: function (form, action) {
                var respJson = Ext.JSON.decode(action.response.responseText);
                toCustomer.setRawValue(respJson.root[0].customer.name);
                sales.setRawValue(respJson.root[0].sales.name);
                sellDept.setRawValue(respJson.root[0].sell_department.name);
                saleType.setRawValue(respJson.root[0].sale_type.name);
                if (respJson.root[0].sales_strategy != undefined) {
                    salesStrategy.setRawValue(respJson.root[0].sales_strategy.name);
                }
                curSaleTypeDiscount = respJson.root[0].sale_type.discount;
                oriSaleTypeDiscount = curSaleTypeDiscount;
                oriSaleTypeId = respJson.root[0].sale_type.id;
            },
            failure: function (form, action) {
                Ext.MessageBox.alert('提示信息', '信息加载失败');
                editSaleOrderAfterAuditWin.destroy();
            }
        });

        saleOrderFormPanel.render('edit_sale_order_after_audit');

        saleOrderDetailGrid.on('edit', afterEdit, this);
        function afterEdit(editor, obj, options) {
            //判断一下用户给产品设置的权限是不是小于他固有权限的折扣。
            roleDiscount = parseFloat(roleDiscount);
            /*if (obj.field=="discount" && obj.record.get('discount') < roleDiscount){
             obj.record.set('discount',roleDiscount);
             }*/
            // execute an XHR to send/commit data to the server, in callback do (if successful):
            //根据当前的销售类型，来计算销售价或折扣
            if (obj.field == "quantity" || obj.field == "unit_price" || obj.field == "discount") {
                if (obj.record.get('quantity') > 0 && obj.record.get('unit_price') > 0) {
                    obj.record.set('amount', Math.round(obj.record.get('quantity') * 1000000 * obj.record.get('unit_price') * obj.record.get('discount')) / 1000000);
                } else {
                    obj.record.set('amount', 0);
                }
            }

            //如果有人提前输入了最终价格，那可以自动算出折扣。
            if (obj.field == "amount") {
                if (obj.record.get('quantity') > 0 && obj.record.get('unit_price') > 0) {
                    obj.record.set('discount', Math.round(obj.record.get('amount') / (obj.record.get('quantity') * 1000 * obj.record.get('unit_price') / 1000) * 1000000) / 1000000);
                } else {
                    obj.record.set('amount', 0);
                }
            }

            getSumAmount();
        }

        function getSumAmount() {
            sumAmount.setValue(0);
            var records = saleOrderDetailDS.getRange(0, saleOrderDetailDS.getCount());
            for (var i = 0; i < records.length; i++) {
                var record = records[i];
                var amount = record.get('amount');
                if (amount === undefined) {
                    amount = 0;
                }
                sumAmount.setValue(sumAmount.getValue() + Number(amount));
            }
        }

        function resetPrice() {
            var records = saleOrderDetailDS.getRange(0, saleOrderDetailDS.getCount());
            for (var i = 0; i < records.length; i++) {
                var record = records[i];
                //如果没有类型价，就设置原始价*折扣，如果有，直接用类型价。
                if (record.get('sale_type_price') == -1) {
                    var unitPirce = Math.round(1000 * record.get('ori_unit_price') * curSaleTypeDiscount) / 1000;
                } else {
                    var unitPirce = record.get('sale_type_price');
                }
                record.set('unit_price', unitPirce);
                record.set('amount', Math.round(10000 * record.get('unit_price') * record.get('quantity') * record.get('discount')) / 10000);
            }
            getSumAmount();
        }
    })
</script>
</head>
<body>
<div id="edit_sale_order_after_audit"></div>
</body>
</html>
